package com.cn.shuangzi.loginplugin.activity;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;

import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.activity.SZInterfaceActivity;
import com.cn.shuangzi.loginplugin.R;
import com.cn.shuangzi.loginplugin.bean.SZUserInfo;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.cn.shuangzi.view.ClearEditText;
import com.google.gson.Gson;

import cn.yzl.countdown_library.CountDownButton;
import io.reactivex.Observable;

/**
 * Created by CN.
 */

public abstract class SZLoginPhoneActivity extends SZBaseActivity implements TextWatcher, SZInterfaceActivity, View.OnClickListener {
    protected ClearEditText edtPhone;
    protected ClearEditText edtCode;
    protected CountDownButton btnGetCode;
    protected Button btnLoginPhone;
    protected String phone;

    @Override
    protected int onGetChildView() {
        return R.layout.activity_login_phone;
    }


    @Override
    protected void onBindChildViews() {
        edtPhone = findViewById(R.id.edtPhone);
        edtCode = findViewById(R.id.edtCode);
        btnGetCode = findViewById(R.id.btnGetCode);
        btnLoginPhone = findViewById(R.id.btnLoginPhone);
    }

    @Override
    protected void onBindChildListeners() {
        edtCode.addTextChangedListener(this);
        edtPhone.addTextChangedListener(this);
        findViewById(R.id.btnGetCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMsgCode();
            }
        });
        findViewById(R.id.btnLoginPhone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
    }

    @Override
    protected void onChildViewCreated() {
        onChildViewCreatedPre();
        btnLoginPhone.setEnabled(false);
        showBackImgLeft(getBackImgLeft());
        setTitleTxt(R.string.txt_login);
    }

    @Override
    protected void onReloadData(boolean isRefresh) {

    }

    private void sendMsgCode() {
        phone = edtPhone.getText().toString().trim();
        if (!SZValidatorUtil.isMobile(phone)) {
            SZToast.warning(getString(R.string.error_plz_input_correct_phone));
            btnGetCode.changeState(CountDownButton.STATE_NORMAL);
            return;
        }
        sendMsgCode(phone);
    }

    public void sendMsgCode(String phone) {
        request(SZRetrofitManager.getInstance().getSZRequest().getVerificationCode(SZApp.getInstance().getSZAppId(), phone), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                closeBar();
                SZToast.success(getString(R.string.success_send_msg_code));
                btnGetCode.start();
                btnLoginPhone.setEnabled(true);
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                closeBar();
                btnGetCode.changeState(CountDownButton.STATE_NORMAL);
            }
        });
    }

    public void showCountDown() {
        btnGetCode.start();
        btnLoginPhone.setEnabled(true);
    }

    public void resetCountDown() {
        btnGetCode.changeState(CountDownButton.STATE_NORMAL);
    }

    public void submit() {
        phone = edtPhone.getText().toString().trim();
        if (!SZValidatorUtil.isMobile(phone)) {
            SZToast.warning(getString(R.string.error_plz_input_correct_phone));
            return;
        }
        String code = edtCode.getText().toString().trim();
        if (!SZValidatorUtil.isValidString(code)) {
            SZToast.warning("请输入验证码！");
            return;
        }
        btnLoginPhone.setEnabled(false);
        login(phone, code);
    }

    public void login(String phone, String code) {
        showBar();
        request(SZRetrofitManager.getInstance().getSZRequest().getTokenByVerificationCode(SZApp.getInstance().getSZAppId(), phone, code), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                Observable observable = getDealTokenObservable(data);
                if(observable == null) {
                    onGetTokenSuccess(data);
                }else{
                    dealToken(observable);
                }
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                btnLoginPhone.setEnabled(true);
                closeBar();
            }
        });
    }

    public void dealToken(Observable observable){
        request(observable, new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                closeBar();
                SZUserInfo userInfo = null;
                try {
                    userInfo = new Gson().fromJson(data, SZUserInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                onDealTokenSuccess(userInfo,data);
            }
            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                btnLoginPhone.setEnabled(true);
                closeBar();
            }
        });
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String phone = edtPhone.getText().toString().trim();
        String code = edtCode.getText().toString().trim();
        if (SZValidatorUtil.isMobile(phone) && SZValidatorUtil.isValidString(code)) {
            btnLoginPhone.setEnabled(true);
        } else {
            btnLoginPhone.setEnabled(false);
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.txtProtocol) {
            startActivity(getProtocolUrl(), getWebViewActivity());
        } else if (i == R.id.txtPrivacy) {
            startActivity(getPrivacyUrl(), getWebViewActivity());
        }
    }

    public abstract Class getWebViewActivity();

    public abstract String getPrivacyUrl();

    public abstract String getProtocolUrl();

    public abstract void onGetTokenSuccess(String token);

    public abstract Observable getDealTokenObservable(String token);

    public abstract void onDealTokenSuccess(SZUserInfo userInfo, String data);
}
